package Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;

import fiuba.descuentos.ActivityBase;
import Helpers.ContextHelper;
import android.app.SearchManager.OnCancelListener;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.AsyncTask;

public class RestServiceFactory extends AsyncTask<Void, Void, JSONObject> {

	private static final String serviceUrl = "http://192.168.209.151/beneficios/trunk/src/web/service/service.php?method=";
	private IService caller;
	public String Method;
	@SuppressWarnings("unchecked")
	public Vector PropertyNames;
	public Vector Values;

	private String error = "";

	@Override
	protected JSONObject doInBackground(Void... ht) {
		try {
			if (! this.isOnline()){
				error = "No tiene internet";
				this.cancel(true);
				return null;
				
			}
			String url = serviceUrl + Method;

			JSONObject jsonResponse = null;
			HttpClient httpclient = new DefaultHttpClient();
			// Prepare a request object
			HttpPost httpPost = new HttpPost(url);
			httpPost.getParams().setParameter("http.socket.timeout",
					new Integer(10000));

			MultipartEntity mulatipartEntity = new MultipartEntity(
					//HttpMultipartMode.BROWSER_COMPATIBLE
					);

			for (int i = 0; i < this.PropertyNames.size(); i++) {

				String value = "";
		
				Parameter param = (Parameter) this.PropertyNames.elementAt(i);
				
				if (param.getType() == 1) {
//					mulatipartEntity.addPart(this.PropertyNames.elementAt(i)
//							.toString(), new FileBody(new File(this.Values
//							.elementAt(i).toString())));
				} else {
					mulatipartEntity.addPart(param.getKey(), new StringBody(param.getValue().toString()));
				}
			}

			httpPost.setEntity(mulatipartEntity);

			HttpResponse response = null;
			response = httpclient.execute(httpPost);
			HttpEntity entity = null;
			// Get hold of the response entity
			entity = response.getEntity();

			if (entity != null) {
				InputStream instream = entity.getContent();
				String r = RestServiceFactory.convertStreamToString(instream);

				jsonResponse = new JSONObject(r);

				int code = response.getStatusLine().getStatusCode();
				if (code != 200) {
					this.cancel(true);
					return null;
				}

				return jsonResponse;
			}
		} catch (Exception ex) {
			error = ex.getMessage();
			this.cancel(true);
			return null;
		}

		return null;
	}

	protected void onCancelled() {

	}

	protected void onPostExecute(JSONObject result) {
		if (this.isCancelled() == true || result == null) {
			 caller.onError(error);
		} else {
			caller.onServiceCompleted(result, this.Method);
		}
	}

	private static String convertStreamToString(InputStream is) {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String cutEnter = sb.toString();
		return cutEnter.replaceAll("\n", "");
	}

	public static void callService(IService caller, String method,
			Vector propertyNames) {
		RestServiceFactory serviceThread = new RestServiceFactory();

		serviceThread.caller = caller;
		serviceThread.Method = method;
		serviceThread.PropertyNames = propertyNames;
		serviceThread.execute(null);
	}

	private RestServiceFactory() {
	}
	
	public boolean isOnline() {
		 ConnectivityManager cm = (ConnectivityManager)ContextHelper.getContextInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
		 if (cm.getActiveNetworkInfo() != null){
			 return cm.getActiveNetworkInfo().isConnectedOrConnecting(); 
		 }

		 return false;
		}

}